package socket

import (
	"github.com/gorilla/websocket"
	"gopkg.in/ffmt.v1"
	"log"
	"time"
	"zsgGin/utils/socket/models"
)

type WsClient struct {
	 conn *websocket.Conn
	 readChan chan *WsMessage          //读队列
	 writeChan chan *models.WsResponse //写队列
	 closeChan chan string             //失败队列
}

func NewWsClient(conn *websocket.Conn) *WsClient {
	return &WsClient{conn: conn,
		readChan:make(chan *WsMessage),
		writeChan:make(chan *models.WsResponse),
		closeChan:make(chan string)}
}


func (ws *WsClient)Ping(waitTime time.Duration) {
	for  {
		err:=ws.conn.WriteMessage(websocket.TextMessage,[]byte("ping"))
		if err!=nil{
			//去除发送不出去的连接
			ClientMap.Remove(ws.conn)
			return
		}
		time.Sleep(waitTime)
	}
}

// ReadLoop 读数据放入通道
func (ws *WsClient)ReadLoop(){
	for  {
		t,data,err:=ws.conn.ReadMessage()
		if err!=nil{
			if er:=ws.conn.Close();er!=nil{
				log.Println("ReadMessage,关闭错误,原因:"+er.Error())
			}
			ClientMap.Remove(ws.conn)
			ws.closeChan<-err.Error()
			break
		}
		ws.readChan<- NewWsMessage(t,data)
	}
}

func (ws  *WsClient) HandlerLoop()  {
	loop:for {
		select {
			case mes:=<-ws.readChan:
				rsp,err:=mes.parseForCmd()
				if err!=nil{
					log.Println(err)
				}
				if rsp!=nil{
					//写入消息
					ws.writeChan<-rsp
				}
			case err:=<-ws.closeChan:
				ffmt.Puts("关闭此次连接:"+err)
				break loop
		}
	}
}


////新增写Loop
//func(ws *WsClient) WriteLoop(){
//	loop:for{
//		select {
//			case msg := <-ws.writeChan:
//				if err := ws.conn.WriteMessage(websocket.TextMessage, msg.ToJson()); err != nil {
//					if er:=ws.conn.Close();err!=nil{
//						log.Println("WriteLoop,关闭错误,原因:"+er.Error())
//					}
//					ClientMap.Remove(ws.conn)
//					ws.closeChan<-errors.New("测试错误").Error()
//					fmt.Println("WriteLoop关闭")
//					break loop  //停止循环
//				}
//				//业务场景
//			}
//	}
//}






